package cn.zyy.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * java 操作数据库的工具类
 */
public final class JDBCUtil {
    private static Connection conn = null;
    private JDBCUtil(){}
    static {
        //获取配置文件参数
        InputStream ins = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties ps = new Properties();
        try {
            ps.load(ins);
            //driver
            String driver = ps.getProperty("jdbc.driver");
            String username = ps.getProperty("jdbc.username");
            String password = ps.getProperty("jdbc.password");
            String url = ps.getProperty("jdbc.url");
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接的方法
    public static Connection getConnection(){
        return conn;
    }
    //释放资源的方法
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {//避免空指针
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
